import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import imageIcon from './icon.svg';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';

export default class ImageBrowsing extends Plugin {
	init() {

		const config = this.editor.config.get('imageBrowsing');

		const editor = this.editor;

		// 初始化定义
		config.init((imageUrl) => {
			if (!imageUrl) {
				return;
			}
			editor.model.change(writer => {
				const imageElement = writer.createElement('image', {
					src: imageUrl
				});

				// Insert the image in the current selection location.
				editor.model.insertContent(imageElement, editor.model.document.selection);
			});
		})

		editor.ui.componentFactory.add('ImageBrowsing', locale => {
			const view = new ButtonView(locale);

			view.set({
				label: '媒体库',
				icon: imageIcon,
				tooltip: true
			});

			// Callback executed once the image is clicked.
			view.on('execute', () => {
				if (!config.open) {
					return;
				}
				config.open()
			});

			return view;
		});

	}
}
